<?php
/**
 * Created by PhpStorm.
 * User: zcq
 * Date: 2018/10/16
 * Time: 15:02
 */

namespace app\admin\service;


use app\admin\model\VoteType;
use think\Validate;

class VoteTypeService extends BaseService
{
    public $model;
    public function __construct()
    {
        parent::__construct();
        $this->model = new VoteType();
    }

    public function getList($voteId)
    {
        return $this->model->where('vote_id',$voteId)->order('id desc')->select();
    }

    public function save($params)
    {
        $validate = new Validate($this->model->rules);
        if(!$validate->check($params))
            return dataReturn(0,$validate->getError());

        $data = [
            'vote_id'=>$params['vote_id'],
            'name' => $params['name'],
            'type_no' => $params['type_no']??'',
            'head_img'=>$params['head_img'],
            'sort'=> $params['sort']??0,
            'enable' => (int)$params['enable']?1:0,
            'modtime'=>time(),
            'addtime'=>time(),
            'pid'=>0,
            'level'=>1,
        ];
        if($params['id']){
            $res = $this->model->where('id',$params['id'])->update($data);
        }else{
            $res = $this->model->insert($data);
        }

        if($res){
            $this->clearVoteType($params['vote_id']);
            return dataReturn(1,'保存成功');
        }else{
            return dataReturn(0,'保存失败');
        }
    }

    public function updateByField($params)
    {
        if($params['field']=='name' && emptys($params['value']))
            return dataReturn(0,'不能为空');

        $data[$params['field']] = $params['value'];
        $data['modtime'] = time();
        $res = $this->model->where('id',$params['id'])->update($data);
        if($res){
            $voteId = $this->model->where('id',$params['id'])->value('vote_id');
            $this->clearVoteType($voteId);
            return dataReturn(1,'保存成功');
        }else{
            return dataReturn(0,'保存失败');
        }
    }

    public function find($id)
    {
        return $this->model->where('id',$id)->find();
    }
}